package com.manager.managersystem.controller;


import com.manager.managersystem.config.redis.RedisService;
import com.manager.managersystem.entity.Permission;
import com.manager.managersystem.entity.User;
import com.manager.managersystem.entity.UserInfo;
import com.manager.managersystem.util.JwtUtils;
import com.manager.managersystem.util.MenuTree;
import com.manager.managersystem.util.Result;
import com.manager.managersystem.vo.RouterVo;
import com.manager.managersystem.vo.TokenVo;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author mao
 * @date 2023/5/5
 * @apiNoto
 */

@RestController
@RequestMapping("/api/sysUser")
public class SysUserController {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisService redisService;

    /**
     * 刷新token
     *
     * @param request
     * @return
     */
    @RequestMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request) {
        //从请求header里获取token
        String token = request.getHeader("token");
        //判断header中是否存在token信息
        if (ObjectUtils.isEmpty(token)) {
            //从请求参数中获取
            token = request.getParameter("token");
        }
        //从SpringSecurity 上下文中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取用户身份信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        //定义变量保存新的token
        String newToken = null;
        //验证提交过来的token是否合法
        if (jwtUtils.validateToken(token, userDetails)) {
            //如果合法生成新的token
            newToken = jwtUtils.refreshToken(token);
        }
        //获取本次token的到期时间
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(newToken.replace("jwt_", ""))
                .getBody().getExpiration().getTime();
        //清除原来的token
        String oldTokenKey = "token_" + token;
        redisService.del(oldTokenKey);
        //将新的token信息保存到redis中
        String newTokenKey = "token_" + newToken;
        redisService.set(newTokenKey, newToken, jwtUtils.getExpiration() / 1000);

        //创建TokenVo对象
        TokenVo tokenVo = new TokenVo(expireTime, newTokenKey);
        //返回数据
        return Result.ok(tokenVo).message("token刷新成功");
    }


    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/getInfo")
    public Result getInfo() {
        //从springsecurity上下文获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //判断用户信息是否为空
        if (authentication == null) {
            return Result.error().message("用户信息查询失败");
        }
        //获取用户信息
        User user = (User) authentication.getPrincipal();
        //获取用户拥有的权限信息
        List<Permission> permissionList = user.getPermissionList();
        //获取权限编码
        Object[] roles = permissionList.stream().filter(Objects::nonNull).map(Permission::getCode).toArray();
        //创建用户信息
        UserInfo userInfo = new UserInfo(user.getId(), user.getNickName(), user.getAvatar(), null, roles);
        return Result.ok(userInfo).message("用户信息查询成功");
    }

    /**
     * 获取菜单数据
     * @return
     */
    @GetMapping("/getMenuList")
    public Result getMenuList() {
        //从Spring Security上下文获取用户信息
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        //获取用户信息
        User user = (User) authentication.getPrincipal();
        //获取相应的权限
        List<Permission> permissionList = user.getPermissionList();
        //筛选目录和菜单
        List<Permission> collect = permissionList.stream()
                .filter(item -> item != null && item.getType() != 2)
                .collect(Collectors.toList());
        //生成路由数据
        List<RouterVo> routerVoList = MenuTree.makeRouter(collect, 0L);
        //返回数据
        return Result.ok(routerVoList).message("菜单数据获取成功");
    }
}
